/**
 * 商品推荐API路由
 */
import express, { type Request, type Response } from 'express';

const router = express.Router();

// 商品接口类型定义
interface Product {
  id: string;
  title: string;
  subtitle?: string;
  description: string;
  price: number;
  originalPrice?: number;
  discount?: number;
  images: string[];
  category: string;
  brand: string;
  tags: string[];
  specifications: {
    name: string;
    value: string;
  }[];
  ageRange: {
    min: number; // 月龄
    max: number;
  };
  rating: number;
  reviewCount: number;
  salesCount: number;
  stock: number;
  isRecommended: boolean;
  isBestseller: boolean;
  isNew: boolean;
  shippingInfo: {
    free: boolean;
    time: string;
  };
  seller: {
    id: string;
    name: string;
    rating: number;
  };
  createdAt: string;
  updatedAt: string;
}

interface Category {
  id: string;
  name: string;
  icon: string;
  productCount: number;
  isHot?: boolean;
}

interface CartItem {
  id: string;
  productId: string;
  userId: string;
  quantity: number;
  selectedSpecs?: Record<string, string>;
  addedAt: string;
}

// 模拟数据存储
let products: Product[] = [
  {
    id: '1',
    title: '婴儿有机米粉',
    subtitle: '营养均衡，易消化',
    description: '采用优质有机大米制作，富含多种维生素和矿物质，专为6个月以上宝宝设计，口感细腻，易于消化吸收。',
    price: 68.00,
    originalPrice: 88.00,
    discount: 23,
    images: [
      'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=organic%20baby%20rice%20cereal%20package&image_size=square',
      'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20eating%20rice%20cereal%20happy&image_size=landscape_4_3'
    ],
    category: '辅食营养',
    brand: '贝因美',
    tags: ['有机', '营养', '易消化', '6个月+'],
    specifications: [
      { name: '净含量', value: '400g' },
      { name: '适用年龄', value: '6-36个月' },
      { name: '保质期', value: '24个月' },
      { name: '储存方式', value: '阴凉干燥处' }
    ],
    ageRange: { min: 6, max: 36 },
    rating: 4.8,
    reviewCount: 1250,
    salesCount: 5600,
    stock: 999,
    isRecommended: true,
    isBestseller: true,
    isNew: false,
    shippingInfo: {
      free: true,
      time: '24小时内发货'
    },
    seller: {
      id: 'seller1',
      name: '贝因美官方旗舰店',
      rating: 4.9
    },
    createdAt: '2024-01-15T08:00:00Z',
    updatedAt: '2024-01-15T08:00:00Z'
  },
  {
    id: '2',
    title: '婴儿推车',
    subtitle: '轻便折叠，安全舒适',
    description: '高景观婴儿推车，可坐可躺，双向推行，轻松折叠，适合0-3岁宝宝使用。配备五点式安全带，确保宝宝安全。',
    price: 899.00,
    originalPrice: 1299.00,
    discount: 31,
    images: [
      'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=modern%20baby%20stroller%20high%20landscape&image_size=square',
      'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20stroller%20folded%20compact&image_size=landscape_4_3'
    ],
    category: '出行用品',
    brand: '好孩子',
    tags: ['高景观', '可折叠', '双向推行', '0-3岁'],
    specifications: [
      { name: '适用年龄', value: '0-36个月' },
      { name: '承重', value: '25kg' },
      { name: '折叠尺寸', value: '85×60×30cm' },
      { name: '重量', value: '8.5kg' }
    ],
    ageRange: { min: 0, max: 36 },
    rating: 4.7,
    reviewCount: 890,
    salesCount: 2300,
    stock: 156,
    isRecommended: true,
    isBestseller: false,
    isNew: true,
    shippingInfo: {
      free: true,
      time: '48小时内发货'
    },
    seller: {
      id: 'seller2',
      name: '好孩子官方店',
      rating: 4.8
    },
    createdAt: '2024-01-18T10:30:00Z',
    updatedAt: '2024-01-18T10:30:00Z'
  },
  {
    id: '3',
    title: '婴儿纸尿裤',
    subtitle: '超薄透气，12小时干爽',
    description: '采用日本进口芯体，超强吸收，瞬间锁水，表面干爽不回渗。弹性腰围设计，贴合宝宝身形，防止侧漏。',
    price: 129.00,
    originalPrice: 159.00,
    discount: 19,
    images: [
      'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20diaper%20package%20soft%20comfortable&image_size=square',
      'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20wearing%20diaper%20happy%20comfortable&image_size=landscape_4_3'
    ],
    category: '尿裤湿巾',
    brand: '花王',
    tags: ['超薄', '透气', '防侧漏', '日本进口'],
    specifications: [
      { name: '规格', value: 'L码' },
      { name: '数量', value: '54片' },
      { name: '适用体重', value: '9-14kg' },
      { name: '材质', value: '无纺布+高分子吸收体' }
    ],
    ageRange: { min: 6, max: 24 },
    rating: 4.9,
    reviewCount: 3200,
    salesCount: 12000,
    stock: 888,
    isRecommended: true,
    isBestseller: true,
    isNew: false,
    shippingInfo: {
      free: true,
      time: '当日发货'
    },
    seller: {
      id: 'seller3',
      name: '花王母婴专营店',
      rating: 4.9
    },
    createdAt: '2024-01-12T14:20:00Z',
    updatedAt: '2024-01-12T14:20:00Z'
  }
];

let categories: Category[] = [
  { id: 'cat1', name: '辅食营养', icon: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20food%20nutrition%20icon&image_size=square', productCount: 156, isHot: true },
  { id: 'cat2', name: '出行用品', icon: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20stroller%20travel%20icon&image_size=square', productCount: 89 },
  { id: 'cat3', name: '尿裤湿巾', icon: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20diaper%20care%20icon&image_size=square', productCount: 234, isHot: true },
  { id: 'cat4', name: '洗护用品', icon: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20bath%20care%20icon&image_size=square', productCount: 123 },
  { id: 'cat5', name: '玩具早教', icon: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20toys%20education%20icon&image_size=square', productCount: 267, isHot: true },
  { id: 'cat6', name: '服装鞋帽', icon: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20clothes%20fashion%20icon&image_size=square', productCount: 345 }
];

let cartItems: CartItem[] = [];

/**
 * 获取商品列表
 * GET /api/product/list
 */
router.get('/list', (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      limit = 10,
      category,
      keyword,
      minPrice,
      maxPrice,
      babyAge,
      sortBy = 'default',
      isRecommended,
      isBestseller,
      isNew
    } = req.query;
    
    let filteredProducts = [...products];
    
    // 分类筛选
    if (category) {
      filteredProducts = filteredProducts.filter(p => p.category === category);
    }
    
    // 关键词搜索
    if (keyword) {
      const kw = (keyword as string).toLowerCase();
      filteredProducts = filteredProducts.filter(p => 
        p.title.toLowerCase().includes(kw) ||
        p.description.toLowerCase().includes(kw) ||
        p.tags.some(tag => tag.toLowerCase().includes(kw))
      );
    }
    
    // 价格筛选
    if (minPrice) {
      filteredProducts = filteredProducts.filter(p => p.price >= Number(minPrice));
    }
    if (maxPrice) {
      filteredProducts = filteredProducts.filter(p => p.price <= Number(maxPrice));
    }
    
    // 年龄筛选
    if (babyAge) {
      const age = Number(babyAge);
      filteredProducts = filteredProducts.filter(p => 
        age >= p.ageRange.min && age <= p.ageRange.max
      );
    }
    
    // 标签筛选
    if (isRecommended === 'true') {
      filteredProducts = filteredProducts.filter(p => p.isRecommended);
    }
    if (isBestseller === 'true') {
      filteredProducts = filteredProducts.filter(p => p.isBestseller);
    }
    if (isNew === 'true') {
      filteredProducts = filteredProducts.filter(p => p.isNew);
    }
    
    // 排序
    switch (sortBy) {
      case 'price_asc':
        filteredProducts.sort((a, b) => a.price - b.price);
        break;
      case 'price_desc':
        filteredProducts.sort((a, b) => b.price - a.price);
        break;
      case 'sales':
        filteredProducts.sort((a, b) => b.salesCount - a.salesCount);
        break;
      case 'rating':
        filteredProducts.sort((a, b) => b.rating - a.rating);
        break;
      case 'newest':
        filteredProducts.sort((a, b) => 
          new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
        );
        break;
      default:
        // 默认排序：推荐 > 销量 > 评分
        filteredProducts.sort((a, b) => {
          if (a.isRecommended !== b.isRecommended) {
            return b.isRecommended ? 1 : -1;
          }
          if (a.salesCount !== b.salesCount) {
            return b.salesCount - a.salesCount;
          }
          return b.rating - a.rating;
        });
    }
    
    // 分页
    const startIndex = (Number(page) - 1) * Number(limit);
    const endIndex = startIndex + Number(limit);
    const paginatedProducts = filteredProducts.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedProducts,
        total: filteredProducts.length,
        page: Number(page),
        limit: Number(limit),
        hasMore: endIndex < filteredProducts.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取商品列表失败'
    });
  }
});

/**
 * 获取商品详情
 * GET /api/product/:id
 */
router.get('/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const product = products.find(p => p.id === id);
    
    if (!product) {
      return res.status(404).json({
        success: false,
        error: '商品不存在'
      });
    }
    
    res.json({
      success: true,
      data: product
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取商品详情失败'
    });
  }
});

/**
 * 获取商品分类
 * GET /api/product/categories
 */
router.get('/categories', (req: Request, res: Response) => {
  try {
    res.json({
      success: true,
      data: categories
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取分类失败'
    });
  }
});

/**
 * 添加到购物车
 * POST /api/product/cart/add
 */
router.post('/cart/add', (req: Request, res: Response) => {
  try {
    const { userId, productId, quantity = 1, selectedSpecs } = req.body;
    
    if (!userId || !productId) {
      return res.status(400).json({
        success: false,
        error: '用户ID和商品ID为必填项'
      });
    }
    
    // 检查商品是否存在
    const product = products.find(p => p.id === productId);
    if (!product) {
      return res.status(404).json({
        success: false,
        error: '商品不存在'
      });
    }
    
    // 检查库存
    if (product.stock < quantity) {
      return res.status(400).json({
        success: false,
        error: '库存不足'
      });
    }
    
    // 检查是否已在购物车中
    const existingItemIndex = cartItems.findIndex(item => 
      item.userId === userId && item.productId === productId
    );
    
    if (existingItemIndex !== -1) {
      // 更新数量
      cartItems[existingItemIndex].quantity += quantity;
    } else {
      // 添加新项目
      const newCartItem: CartItem = {
        id: Date.now().toString(),
        productId,
        userId,
        quantity,
        selectedSpecs,
        addedAt: new Date().toISOString()
      };
      cartItems.push(newCartItem);
    }
    
    res.json({
      success: true,
      message: '添加到购物车成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '添加到购物车失败'
    });
  }
});

/**
 * 获取购物车
 * GET /api/product/cart/:userId
 */
router.get('/cart/:userId', (req: Request, res: Response) => {
  try {
    const { userId } = req.params;
    
    const userCartItems = cartItems.filter(item => item.userId === userId);
    
    // 补充商品信息
    const cartWithProducts = userCartItems.map(item => {
      const product = products.find(p => p.id === item.productId);
      return {
        ...item,
        product
      };
    }).filter(item => item.product); // 过滤掉商品不存在的项目
    
    res.json({
      success: true,
      data: cartWithProducts
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取购物车失败'
    });
  }
});

/**
 * 更新购物车商品数量
 * PUT /api/product/cart/:id
 */
router.put('/cart/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { quantity } = req.body;
    
    const itemIndex = cartItems.findIndex(item => item.id === id);
    if (itemIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '购物车项目不存在'
      });
    }
    
    if (quantity <= 0) {
      // 删除项目
      cartItems.splice(itemIndex, 1);
    } else {
      // 更新数量
      cartItems[itemIndex].quantity = quantity;
    }
    
    res.json({
      success: true,
      message: '更新成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '更新购物车失败'
    });
  }
});

/**
 * 删除购物车商品
 * DELETE /api/product/cart/:id
 */
router.delete('/cart/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    const itemIndex = cartItems.findIndex(item => item.id === id);
    if (itemIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '购物车项目不存在'
      });
    }
    
    cartItems.splice(itemIndex, 1);
    
    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '删除购物车商品失败'
    });
  }
});

/**
 * 获取推荐商品
 * GET /api/product/recommend
 */
router.get('/recommend', (req: Request, res: Response) => {
  try {
    const { userId, babyAge, limit = 10 } = req.query;
    
    let recommendedProducts = products.filter(p => p.isRecommended);
    
    // 根据宝宝年龄筛选
    if (babyAge) {
      const age = Number(babyAge);
      recommendedProducts = recommendedProducts.filter(p => 
        age >= p.ageRange.min && age <= p.ageRange.max
      );
    }
    
    // 按评分和销量排序
    recommendedProducts.sort((a, b) => {
      const scoreA = a.rating * 0.6 + (a.salesCount / 1000) * 0.4;
      const scoreB = b.rating * 0.6 + (b.salesCount / 1000) * 0.4;
      return scoreB - scoreA;
    });
    
    // 限制数量
    recommendedProducts = recommendedProducts.slice(0, Number(limit));
    
    res.json({
      success: true,
      data: recommendedProducts
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取推荐商品失败'
    });
  }
});

export default router;